package com.hy.aicodegeneration.langgraph4j.tools;

import cn.hutool.core.util.StrUtil;
import com.hy.aicodegeneration.langgraph4j.enums.ImageCategoryEnum;
import com.hy.aicodegeneration.langgraph4j.model.ImageCollectionResult;
import com.hy.aicodegeneration.langgraph4j.model.ImageResource;
import com.hy.aicodegeneration.manager.CosManager;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.ArrayList;
import java.util.List;

/**
 * Mermaid 图表生成工具
 * 将 Mermaid 代码转换为图片
 */
@Slf4j
@Component
public class MermaidDiagramTool {

    private final CosManager cosManager;

    public MermaidDiagramTool(CosManager cosManager) {
        this.cosManager = cosManager;
    }

    @Tool("将 Mermaid 代码转换为架构图，用于展示系统结构和技术关系")
    public ImageCollectionResult generateMermaidDiagram(
            @P("Mermaid 图表代码") String mermaidCode,
            @P("架构图描述") String description) {
        try {
            // 生成简单的占位图（实际项目中应该调用 Mermaid API 生成图表）
            BufferedImage diagramImage = createPlaceholderDiagram(400, 300);
            // 转换为 Base64
            String base64Image = imageToBase64(diagramImage, "png");
            // 构造 Data URL
            String dataUrl = "data:image/png;base64," + base64Image;
            // 构造图片资源对象
            ImageResource imageResource = ImageResource.builder()
                    .category(ImageCategoryEnum.ARCHITECTURE)
                    .description(description)
                    .url(dataUrl)
                    .build();
            
            List<ImageResource> imageList = new ArrayList<>();
            imageList.add(imageResource);
            return new ImageCollectionResult(imageList);
        } catch (Exception e) {
            log.error("Mermaid 图表生成失败: {}", e.getMessage(), e);
            return new ImageCollectionResult(new ArrayList<>());
        }
    }

    /**
     * 创建简单的占位图
     *
     * @param width  宽度
     * @param height 高度
     * @return BufferedImage 对象
     */
    private BufferedImage createPlaceholderDiagram(int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        java.awt.Graphics2D g2d = image.createGraphics();

        // 设置背景色
        g2d.setColor(java.awt.Color.LIGHT_GRAY);
        g2d.fillRect(0, 0, width, height);

        // 绘制简单的占位图
        g2d.setColor(java.awt.Color.GRAY);
        g2d.drawRect(50, 50, width - 100, height - 100);
        g2d.drawLine(50, 50, width - 50, height - 50);
        g2d.drawLine(50, height - 50, width - 50, 50);

        g2d.dispose();
        return image;
    }

    /**
     * 将 BufferedImage 转换为 Base64 字符串
     *
     * @param image    BufferedImage 对象
     * @param format   图片格式（如 "png", "jpg"）
     * @return Base64 编码的字符串
     * @throws IOException IO异常
     */
    private String imageToBase64(BufferedImage image, String format) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, format, baos);
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }
}